import flask
from flask import Flask, render_template

import config
import service
from db import db

from predict import name_predict

app = Flask(__name__, static_url_path='/statics', static_folder='./statics', template_folder='./templates')
app.config.from_object(config)
db.init_app(app)


@app.route('/', methods=["GET"])
def index():
    """
    get入口，转发到index.html
    :return:
    """
    return render_template('index.html')


@app.route("/", methods=["POST"])
def predict():
    """
    主视图函数
    :return:
    """
    try:
        # 请求服务器的日志写入数据库
        service.log_request()
    except Exception as e:
        print(e)
    # 接收POST传入的参数
    params = flask.request.json
    if (not params) or 'name' not in params:
        resp = {'err': '缺少参数'}
    else:
        name = params.get('name')
        if 0 < len(name) <= 5:
            try:
                resp = name_predict(name)
            except AssertionError as e:
                resp = {'err': str(e)}
        else:
            resp = {'err': '名字长度必须小于5'}
    return flask.jsonify(resp)


if __name__ == '__main__':
    # 启动服务器
    app.run(host='0.0.0.0', port=8080)
